package com.evildog.workspace.file.upload.uploader;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.evildog.workspace.common.exception.ServerErrorException;
import com.evildog.workspace.file.enums.FileCustomExceptionDesc;
import com.evildog.workspace.file.upload.object.VirtualFileDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
public abstract class AbstractFileUploader implements FileUploader {

    private static final DateTimeFormatter df = DateTimeFormatter.ofPattern(DatePattern.PURE_DATETIME_MS_PATTERN);

    String createNewFilename(String originalName) {
        String suffix = FileUtil.getSuffix(originalName);
        return LocalDateTime.now().format(df) + RandomUtil.randomString(4) + "." + suffix;
    }

    @Override
    public VirtualFileDTO upload(MultipartFile file, String folder){
        try {
            return upload(file.getInputStream(),file.getOriginalFilename(), folder);
        } catch (IOException e) {
            log.error("upload file error:", e);
            throw new ServerErrorException(FileCustomExceptionDesc.MULTI_FILE_UPLOAD_FAILED);
        }

    }

    @Override
    public VirtualFileDTO upload(File file, String folder){
        try {
            return upload(new FileInputStream(file),file.getName(), folder);
        } catch (IOException e) {
            log.error("upload file error:", e);
            throw new ServerErrorException(FileCustomExceptionDesc.NORMAL_FILE_UPLOAD_FAILED);
        }
    }

}
